﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetMicro.Core.Extensions;

namespace NetMicro.EventBus.Kafka
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加kafka注册  properties see: https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
        /// </summary>
        /// <param name="eventBusBuilder"></param>
        /// <param name="configurationSection"></param>
        /// <returns></returns>
        public static IEventBusBuilder AddKafka(this IEventBusBuilder eventBusBuilder,
            IConfigurationSection configurationSection)
        {
            if (configurationSection is null) throw new ArgumentNullException(nameof(configurationSection));
            eventBusBuilder.Services.Configure<EventBusKafkaOptions>(configurationSection);
            return eventBusBuilder.AddKafkaCore();
        }

        /// <summary>
        ///  添加kafka注册  properties see: https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
        /// </summary>
        /// <param name="eventBusBuilder"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static IEventBusBuilder AddKafka(this IEventBusBuilder eventBusBuilder,
            Action<EventBusKafkaOptions> action)
        {
            if (action is null) throw new ArgumentNullException(nameof(action));
            eventBusBuilder.Services.Configure(action);
            return eventBusBuilder.AddKafkaCore();
        }

        /// <summary>
        ///  添加kafka注册
        /// </summary>
        /// <param name="eventBusBuilder"></param>
        /// <param name="server"></param>
        /// <returns></returns>
        public static IEventBusBuilder AddKafka(this IEventBusBuilder eventBusBuilder, string server)
        {
            if (string.IsNullOrWhiteSpace(server))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(server));
            return eventBusBuilder.AddKafka(r => { r.Properties.Add("bootstrap.servers", server); });
        }

        /// <summary>
        /// 添加kafka注册
        /// </summary>
        /// <param name="eventBusBuilder"></param>
        /// <returns></returns>
        private static IEventBusBuilder AddKafkaCore(this IEventBusBuilder eventBusBuilder)
        {
            eventBusBuilder.Services.AddOptions<EventBusKafkaOptions>();
            eventBusBuilder.Services.AddSingleton<IMessageSender, KafkaMessageSender>();
            eventBusBuilder.Services.AddSingleton<IEventSubscriber, KafkaEventSubscriber>();
            eventBusBuilder.Services.AddSingleton<IKafkaConnection, KafkaConnection>();

            return eventBusBuilder;
        }

     
    }
}